/**
 * 支付流程集成测试脚本
 * 用于测试完整的支付流程功能
 */

const axios = require('axios');
const mongoose = require('mongoose');
require('dotenv').config();

// 测试配置
const BASE_URL = 'http://localhost:3002/api';
const TEST_USER = {
  email: 'test@example.com',
  password: 'test123456'
};

let authToken = '';
let testOrderId = '';
let testPaymentId = '';

// API 请求封装
const api = {
  post: async (url, data, headers = {}) => {
    const response = await axios.post(`${BASE_URL}${url}`, data, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': authToken ? `Bearer ${authToken}` : '',
        ...headers
      }
    });
    return response.data;
  },
  
  get: async (url, headers = {}) => {
    const response = await axios.get(`${BASE_URL}${url}`, {
      headers: {
        'Authorization': authToken ? `Bearer ${authToken}` : '',
        ...headers
      }
    });
    return response.data;
  },
  
  put: async (url, data, headers = {}) => {
    const response = await axios.put(`${BASE_URL}${url}`, data, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': authToken ? `Bearer ${authToken}` : '',
        ...headers
      }
    });
    return response.data;
  }
};

// 测试步骤
const tests = {
  // 1. 用户登录
  async login() {
    console.log('🔐 测试用户登录...');
    try {
      const result = await api.post('/users/login', TEST_USER);
      authToken = result.token;
      console.log('✅ 登录成功');
      return true;
    } catch (error) {
      console.log('❌ 登录失败:', error.response?.data?.message || error.message);
      return false;
    }
  },

  // 2. 创建测试订单
  async createOrder() {
    console.log('📦 创建测试订单...');
    try {
      const orderData = {
        orderItems: [
          {
            product: '507f1f77bcf86cd799439011', // 测试商品ID
            name: '测试商品',
            image: 'https://example.com/test.jpg',
            price: 99.99,
            qty: 1
          }
        ],
        shippingAddress: {
          name: '测试用户',
          phone: '13800138000',
          province: '北京市',
          city: '北京市',
          district: '朝阳区',
          address: '测试地址123号'
        },
        paymentMethod: 'alipay',
        itemsPrice: 99.99,
        taxPrice: 0,
        shippingPrice: 10,
        totalPrice: 109.99
      };

      const result = await api.post('/orders', orderData);
      testOrderId = result._id;
      console.log('✅ 订单创建成功，订单ID:', testOrderId);
      return true;
    } catch (error) {
      console.log('❌ 创建订单失败:', error.response?.data?.message || error.message);
      return false;
    }
  },

  // 3. 创建支付订单
  async createPayment() {
    console.log('💳 创建支付订单...');
    try {
      const paymentData = {
        orderId: testOrderId,
        paymentMethod: 'alipay'
      };

      const result = await api.post('/payments/create', paymentData);
      testPaymentId = result.paymentId;
      console.log('✅ 支付订单创建成功');
      console.log('   支付ID:', testPaymentId);
      console.log('   支付URL:', result.paymentUrl);
      return true;
    } catch (error) {
      console.log('❌ 创建支付订单失败:', error.response?.data?.message || error.message);
      return false;
    }
  },

  // 4. 查询支付状态
  async checkPaymentStatus() {
    console.log('🔍 查询支付状态...');
    try {
      const result = await api.get(`/payments/${testPaymentId}/status`);
      console.log('✅ 支付状态查询成功');
      console.log('   状态:', result.status);
      console.log('   金额:', result.amount / 100, '元');
      return true;
    } catch (error) {
      console.log('❌ 查询支付状态失败:', error.response?.data?.message || error.message);
      return false;
    }
  },

  // 5. 模拟支付回调
  async simulatePaymentCallback() {
    console.log('📞 模拟支付回调...');
    try {
      // 这里模拟支付宝回调数据
      const callbackData = {
        out_trade_no: `PAY${Date.now()}TEST`,
        trade_no: `ALIPAY${Date.now()}`,
        trade_status: 'TRADE_SUCCESS',
        total_amount: '109.99',
        subject: '测试订单支付'
      };

      // 注意：实际环境中这个接口不需要认证
      const result = await api.post('/payments/alipay/notify', callbackData, {
        'Authorization': '' // 移除认证头
      });
      
      console.log('✅ 支付回调处理成功');
      return true;
    } catch (error) {
      console.log('❌ 支付回调处理失败:', error.response?.data?.message || error.message);
      return false;
    }
  },

  // 6. 获取订单列表
  async getOrderList() {
    console.log('📋 获取订单列表...');
    try {
      const result = await api.get('/orders');
      console.log('✅ 订单列表获取成功');
      console.log('   订单数量:', result.orders?.length || result.length);
      return true;
    } catch (error) {
      console.log('❌ 获取订单列表失败:', error.response?.data?.message || error.message);
      return false;
    }
  },

  // 7. 获取订单详情
  async getOrderDetail() {
    console.log('📄 获取订单详情...');
    try {
      const result = await api.get(`/orders/${testOrderId}`);
      console.log('✅ 订单详情获取成功');
      console.log('   订单号:', result.orderNo);
      console.log('   订单状态:', result.orderStatus);
      console.log('   支付状态:', result.isPaid ? '已支付' : '未支付');
      return true;
    } catch (error) {
      console.log('❌ 获取订单详情失败:', error.response?.data?.message || error.message);
      return false;
    }
  }
};

// 运行测试
async function runTests() {
  console.log('🚀 开始支付流程集成测试\n');
  
  const testSteps = [
    'login',
    'createOrder',
    'createPayment',
    'checkPaymentStatus',
    'getOrderList',
    'getOrderDetail'
  ];

  let passedTests = 0;
  
  for (const step of testSteps) {
    const success = await tests[step]();
    if (success) {
      passedTests++;
    }
    console.log(''); // 空行分隔
  }

  console.log('📊 测试结果:');
  console.log(`   通过: ${passedTests}/${testSteps.length}`);
  console.log(`   成功率: ${(passedTests / testSteps.length * 100).toFixed(1)}%`);
  
  if (passedTests === testSteps.length) {
    console.log('🎉 所有测试通过！');
  } else {
    console.log('⚠️  部分测试失败，请检查相关功能');
  }
}

// 启动测试
if (require.main === module) {
  runTests().catch(console.error);
}

module.exports = { runTests, tests };
